package com.example.houseitemmanagebackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.houseitemmanagebackend.entity.Category;
import com.example.houseitemmanagebackend.entity.Items;
import com.example.houseitemmanagebackend.exception.BusinessException;
import com.example.houseitemmanagebackend.mapper.CategoryMapper;
import com.example.houseitemmanagebackend.mapper.ItemMapper;
import com.example.houseitemmanagebackend.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 分类服务实现类
 */
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private ItemMapper itemMapper;

    @Override
    @Cacheable(value = "categoryList", key = "#userId")
    public List<Category> getCategoryList(Integer userId) {
        // 查询系统预设分类和用户自定义分类
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getIsSystem, 1)
                .or()
                .eq(Category::getUserId, userId);

        queryWrapper.orderByAsc(Category::getIsSystem).orderByDesc(Category::getCreatedAt);

        return categoryMapper.selectList(queryWrapper);
    }

    @Override
    @Transactional
    @CacheEvict(value = "categoryList", key = "#userId")
    public Integer addCategory(String name, Integer userId) {
        // 检查分类名称是否已存在
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getName, name)
                .and(wrapper -> wrapper.eq(Category::getUserId, userId).or().eq(Category::getIsSystem, 1));

        if (categoryMapper.selectCount(queryWrapper) > 0) {
            throw new BusinessException(400, "分类名称已存在");
        }

        // 创建新分类
        Category category = new Category();
        category.setName(name);
        category.setUserId(userId);
        category.setIsSystem(0); // 非系统预设
        category.setCreatedAt(LocalDateTime.now());
        category.setUpdatedAt(LocalDateTime.now());

        categoryMapper.insert(category);

        return category.getId();
    }

    @Override
    @Transactional
    @CacheEvict(value = "categoryList", key = "#userId")
    public void updateCategory(Integer id, String name, Integer userId) {
        // 检查分类是否存在
        Category category = categoryMapper.selectById(id);
        if (category == null) {
            throw new BusinessException(404, "分类不存在");
        }

        // 检查是否有权限操作（只能修改自己创建的非系统分类）
        if (category.getIsSystem() == 1 || !category.getUserId().equals(userId)) {
            throw new BusinessException(403, "无权限操作此分类");
        }

        // 检查新名称是否与其他分类重复
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getName, name)
                .and(wrapper -> wrapper.eq(Category::getUserId, userId).or().eq(Category::getIsSystem, 1))
                .ne(Category::getId, id);

        if (categoryMapper.selectCount(queryWrapper) > 0) {
            throw new BusinessException(400, "分类名称已存在");
        }

        // 更新分类
        category.setName(name);
        category.setUpdatedAt(LocalDateTime.now());

        categoryMapper.updateById(category);
    }

    @Override
    @Transactional
    @CacheEvict(value = "categoryList", key = "#userId")
    public void deleteCategory(Integer id, Integer userId) {
        // 检查分类是否存在
        Category category = categoryMapper.selectById(id);
        if (category == null) {
            throw new BusinessException(404, "分类不存在");
        }

        // 检查是否有权限操作（只能删除自己创建的非系统分类）
        if (category.getIsSystem() == 1 || !category.getUserId().equals(userId)) {
            throw new BusinessException(403, "无权限操作此分类");
        }

        // 检查是否有物品使用此分类
        LambdaQueryWrapper<Items> itemQueryWrapper = new LambdaQueryWrapper<>();
        itemQueryWrapper.eq(Items::getCategoryId, id);

        long count = itemMapper.selectCount(itemQueryWrapper);
        if (count > 0) {
            throw new BusinessException(400, "该分类下存在物品，无法删除");
        }

        // 删除分类
        categoryMapper.deleteById(id);
    }
}